package com.dzt.androidframework.database.tasks;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.dzt.androidframework.R;
import com.dzt.androidframework.adapter.AbsListAdapter;
import com.dzt.androidframework.database.javabean.Task;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by M02323 on 2017/6/10.
 */

public class TasksAdapter extends AbsListAdapter<Task>{
	private TaskItemListener mItemListener;

	public TasksAdapter(Context context, List<Task> datas, TaskItemListener itemListener) {
		super(context, datas);
		setList(datas);
		this.mItemListener = itemListener;
	}

	public void replaceData(List<Task> tasks) {
		setList(tasks);
		notifyDataSetChanged();
	}

	private void setList(List<Task> tasks) {
		datas = checkNotNull(tasks);
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if(convertView == null){
			holder = new ViewHolder();
			convertView = layoutInflater.inflate(R.layout.task_item, parent, false);
			x.view().inject(holder, convertView);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
		final Task task = datas.get(position);

		holder.tvTitle.setText(task.getTitleForList());

		// Active/completed task UI
		holder.checkBox.setChecked(task.isCompleted());
		if (task.isCompleted()) {
			convertView.setBackgroundResource(R.drawable.list_completed_touch_feedback);
		} else {
			convertView.setBackgroundResource(R.drawable.touch_feedback);
		}
		holder.checkBox.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!task.isCompleted()) {
					mItemListener.onCompleteTaskClick(task);
				} else {
					mItemListener.onActivateTaskClick(task);
				}
			}
		});

		convertView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				mItemListener.onTaskClick(task);
			}
		});
		return convertView;
	}

	class ViewHolder{
		@ViewInject(R.id.complete)
		CheckBox checkBox;
		@ViewInject(R.id.title)
		TextView tvTitle;
	}

	public interface TaskItemListener {
		void onTaskClick(Task clickedTask);
		void onCompleteTaskClick(Task completedTask);
		void onActivateTaskClick(Task activatedTask);
	}
}
